﻿using SuperX.Common.Collection;
using SuperX.Common;
using System;
using System.Collections.Generic;
using System.Linq;

namespace SuperX.MiddlewareBase
{
    public abstract class ServerBase : BasicObjCollection<IBasicObject>
    {
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnable { get; set; } = false;

        /// <summary>
        /// 主机
        /// </summary>
        public string HostIP { get; set; }

        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; set; }

        public abstract void Init();

        public virtual void Stop()
        {
            foreach (var item in Channels)
            {
                item?.Stop();
            }
        }

        private ListObjectCollection<ServerBase, ChannelBase> _channels;

        public ListObjectCollection<ServerBase, ChannelBase> Channels
        {
            get => _channels ?? (_channels = new ListObjectCollection<ServerBase, ChannelBase>(this));
            set
            {
                _channels = value;
                _channels.SetParent(this);
            }
        }

        public virtual void CheckChannel()
        {
        }

        #region IBasicObject

        public override IBasicObject this[string name] => Channels.Values.FirstOrDefault(a => a.Name == name);

        public override List<string> GetKeys()
        {
            return Channels.Values.Select(a => a.Name).ToList();
        }

        public override List<IBasicObject> GetValues()
        {
            return Channels.Values.OfType<IBasicObject>().ToList();
        }

        public override bool IsUniqueName(string name, IObjCollection parent)
        {
            if (parent != null)
            {
                return parent.IsUniqueName(name, null);
            }

            return true;
        }

        #endregion IBasicObject
    }
}